#include "room.hpp"
#include "protocol_dist.hpp"
using namespace std;
using namespace winux;

Room::Room() 
{
}

bool Room::hasUser(User *user)
{
    for (auto member : userList)
    {
        if (member == user)
        {
            return true;
        }
    }
    return false;
}

void Room::userEnter(User *user)
{
    if (!ArrayHas(userList, user))
    {
        userList.push_back(user);
    }
    if (owner.empty() && !userList.empty())
    {
        owner = userList[0]->token;
    }
    ProtocolS2CUpdateRoom rtn;
    rtn.room = this->toProtocol();
    this->dispatch(&rtn);
}
void Room::userLeave(User *user)
{
    if (!hasUser(user))
    {
        return;
    }
    if (this->owner == user->token)
    {
        this->owner = "";
    }
    ArrayRemove(userList, user);
    if (owner.empty() && !userList.empty())
    {
        owner = userList[0]->token;
    }
    ProtocolS2CUpdateRoom rtn;
    rtn.room = this->toProtocol();
    this->dispatch(&rtn);
}

void Room::dispatch(Protocol *msg, User *sender)
{
    for (auto user : userList)
    {
        if (sender != user)
        {
            user->send(msg);
        }
    }
}

winux::SimplePointer<ProtocolObjectRoom> Room::toProtocol()
{
    winux::SimplePointer<ProtocolObjectRoom> p;
    p.attachNew(new ProtocolObjectRoom());
    p->id = this->id;
    p->owner = this->owner;
    for (auto user : this->userList)
    {
        PTR_REF(pUserData, userData, ProtocolObjectUser);
        userData.sessionTime = user->sessionTime;
        userData.token = user->token;
        p->userList.push_back(pUserData);
    }
    return p;
}